/**
 * 报警数据管理模块
 * 处理报警信息的存储、查询和分析
 */

/**
 * 报警数据结构定义
 */
export const AlarmDataStructure = {
  // 基本信息
  id: '',                    // 唯一标识符
  timestamp: 0,              // 报警时间戳
  type: '',                  // 报警类型
  level: '',                 // 严重等级
  status: '',                // 处理状态
  
  // 位置信息
  location: {
    latitude: 0,             // 纬度
    longitude: 0,            // 经度
    accuracy: 0,             // 精度
    address: '',             // 详细地址
    building: '',            // 建筑物
    floor: '',               // 楼层
    room: ''                 // 房间
  },
  
  // 设备信息
  device: {
    id: '',                  // 设备ID
    name: '',                // 设备名称
    type: '',                // 设备类型
    version: '',             // 固件版本
    battery: 0,              // 电池电量
    signal: 0                // 信号强度
  },
  
  // 音频数据
  audioData: {
    decibel: 0,              // 分贝值
    frequency: 0,            // 频率
    duration: 0,             // 持续时间
    pattern: '',             // 声音模式
    confidence: 0,           // 识别置信度
    audioFile: ''            // 音频文件路径
  },
  
  // 视频数据
  videoData: {
    hasVideo: false,         // 是否有视频
    videoFile: '',           // 视频文件路径
    thumbnails: [],          // 缩略图
    duration: 0,             // 视频时长
    resolution: ''           // 分辨率
  },
  
  // 传感器数据
  sensorData: {
    motion: false,           // 运动检测
    temperature: 0,          // 温度
    humidity: 0,             // 湿度
    light: 0,                // 光照强度
    vibration: 0             // 震动强度
  },
  
  // 证据信息
  evidence: {
    photos: [],              // 照片列表
    recordings: [],          // 录音列表
    videos: [],              // 视频列表
    documents: [],           // 文档列表
    hash: '',                // 数据哈希值
    signature: ''            // 数字签名
  },
  
  // 处理信息
  handling: {
    handled: false,          // 是否已处理
    handlerId: '',           // 处理人ID
    handlerName: '',         // 处理人姓名
    handleTime: 0,           // 处理时间
    handleNotes: '',         // 处理备注
    resolution: ''           // 解决方案
  }
}

/**
 * 报警类型定义
 */
const AlarmTypes = {
  VERBAL_BULLYING: {
    code: 'verbal_bullying',
    name: '言语欺凌',
    description: '辱骂、威胁、嘲笑等言语攻击',
    color: '#ff9800',
    icon: 'volume-o'
  },
  PHYSICAL_BULLYING: {
    code: 'physical_bullying', 
    name: '身体欺凌',
    description: '推搡、打击、暴力等身体攻击',
    color: '#f44336',
    icon: 'warning-o'
  },
  SOCIAL_BULLYING: {
    code: 'social_bullying',
    name: '社交欺凌',
    description: '孤立、排挤、传播谣言等社交攻击',
    color: '#9c27b0',
    icon: 'friends-o'
  },
  CYBER_BULLYING: {
    code: 'cyber_bullying',
    name: '网络欺凌',
    description: '网络骚扰、传播不当内容等',
    color: '#3f51b5',
    icon: 'phone-o'
  },
  EMERGENCY: {
    code: 'emergency',
    name: '紧急情况',
    description: '需要立即干预的紧急情况',
    color: '#d32f2f',
    icon: 'fire-o'
  },
  SUSPICIOUS: {
    code: 'suspicious',
    name: '可疑活动',
    description: '疑似不当行为，需要关注',
    color: '#ff5722',
    icon: 'eye-o'
  }
}

/**
 * 严重等级定义
 */
const SeverityLevels = {
  LOW: {
    code: 'low',
    name: '轻微',
    value: 1,
    color: '#4caf50',
    description: '轻微异常，建议关注'
  },
  MEDIUM: {
    code: 'medium',
    name: '中等',
    value: 2,
    color: '#ff9800',
    description: '中等风险，需要处理'
  },
  HIGH: {
    code: 'high',
    name: '严重',
    value: 3,
    color: '#f44336',
    description: '严重情况，优先处理'
  },
  CRITICAL: {
    code: 'critical',
    name: '紧急',
    value: 4,
    color: '#d32f2f',
    description: '紧急情况，立即处理'
  }
}

/**
 * 报警数据管理类
 */
class AlarmDataManager {
  constructor() {
    this.storageKey = 'alarmRecords'
    this.maxRecords = 1000
  }

  /**
   * 创建新的报警记录
   */
  createAlarmRecord(data) {
    const record = {
      id: this.generateId(),
      timestamp: Date.now(),
      type: data.type || 'suspicious',
      level: data.level || 'medium',
      status: 'active',
      
      location: {
        latitude: data.latitude || 0,
        longitude: data.longitude || 0,
        accuracy: data.accuracy || 0,
        address: data.address || '',
        building: data.building || '',
        floor: data.floor || '',
        room: data.room || ''
      },
      
      device: {
        id: data.deviceId || '',
        name: data.deviceName || '',
        type: data.deviceType || 'sensor',
        version: data.deviceVersion || '',
        battery: data.battery || 100,
        signal: data.signal || 100
      },
      
      audioData: {
        decibel: data.decibel || 0,
        frequency: data.frequency || 0,
        duration: data.duration || 0,
        pattern: data.pattern || '',
        confidence: data.confidence || 0,
        audioFile: data.audioFile || ''
      },
      
      videoData: {
        hasVideo: data.hasVideo || false,
        videoFile: data.videoFile || '',
        thumbnails: data.thumbnails || [],
        duration: data.videoDuration || 0,
        resolution: data.resolution || ''
      },
      
      sensorData: {
        motion: data.motion || false,
        temperature: data.temperature || 20,
        humidity: data.humidity || 50,
        light: data.light || 300,
        vibration: data.vibration || 0
      },
      
      evidence: {
        photos: data.photos || [],
        recordings: data.recordings || [],
        videos: data.videos || [],
        documents: data.documents || [],
        hash: this.generateHash(data),
        signature: this.generateSignature(data)
      },
      
      handling: {
        handled: false,
        handlerId: '',
        handlerName: '',
        handleTime: 0,
        handleNotes: '',
        resolution: ''
      }
    }
    
    return record
  }

  /**
   * 保存报警记录
   */
  saveAlarmRecord(record) {
    try {
      let records = this.getAlarmRecords()
      records.unshift(record)
      
      // 限制最大记录数
      if (records.length > this.maxRecords) {
        records = records.slice(0, this.maxRecords)
      }
      
      wx.setStorageSync(this.storageKey, records)
      
      // 触发全局事件
      this.notifyRecordSaved(record)
      
      return true
    } catch (error) {
      console.error('保存报警记录失败:', error)
      return false
    }
  }

  /**
   * 获取所有报警记录
   */
  getAlarmRecords() {
    try {
      return wx.getStorageSync(this.storageKey) || []
    } catch (error) {
      console.error('获取报警记录失败:', error)
      return []
    }
  }

  /**
   * 根据ID获取报警记录
   */
  getAlarmById(id) {
    const records = this.getAlarmRecords()
    return records.find(record => record.id === id)
  }

  /**
   * 按时间范围查询
   */
  getAlarmsByTimeRange(startTime, endTime) {
    const records = this.getAlarmRecords()
    return records.filter(record => 
      record.timestamp >= startTime && record.timestamp <= endTime
    )
  }

  /**
   * 按类型查询
   */
  getAlarmsByType(type) {
    const records = this.getAlarmRecords()
    return records.filter(record => record.type === type)
  }

  /**
   * 按严重等级查询
   */
  getAlarmsByLevel(level) {
    const records = this.getAlarmRecords()
    return records.filter(record => record.level === level)
  }

  /**
   * 获取未处理的报警
   */
  getUnhandledAlarms() {
    const records = this.getAlarmRecords()
    return records.filter(record => !record.handling.handled)
  }

  /**
   * 更新报警处理状态
   */
  updateAlarmHandling(id, handlingData) {
    try {
      let records = this.getAlarmRecords()
      const index = records.findIndex(record => record.id === id)
      
      if (index !== -1) {
        records[index].handling = {
          ...records[index].handling,
          ...handlingData,
          handleTime: Date.now()
        }
        
        if (handlingData.handled) {
          records[index].status = 'resolved'
        }
        
        wx.setStorageSync(this.storageKey, records)
        return true
      }
      
      return false
    } catch (error) {
      console.error('更新报警处理状态失败:', error)
      return false
    }
  }

  /**
   * 获取统计数据
   */
  getStatistics(days = 30) {
    const records = this.getAlarmRecords()
    const startTime = Date.now() - (days * 24 * 60 * 60 * 1000)
    const recentRecords = records.filter(record => record.timestamp >= startTime)
    
    const stats = {
      total: recentRecords.length,
      handled: recentRecords.filter(r => r.handling.handled).length,
      unhandled: recentRecords.filter(r => !r.handling.handled).length,
      byType: {},
      byLevel: {},
      byDay: {}
    }
    
    // 按类型统计
    Object.keys(AlarmTypes).forEach(key => {
      const type = AlarmTypes[key]
      stats.byType[type.code] = recentRecords.filter(r => r.type === type.code).length
    })
    
    // 按等级统计
    Object.keys(SeverityLevels).forEach(key => {
      const level = SeverityLevels[key]
      stats.byLevel[level.code] = recentRecords.filter(r => r.level === level.code).length
    })
    
    // 按天统计
    for (let i = 0; i < days; i++) {
      const dayStart = startTime + (i * 24 * 60 * 60 * 1000)
      const dayEnd = dayStart + (24 * 60 * 60 * 1000)
      const dayKey = new Date(dayStart).toISOString().split('T')[0]
      stats.byDay[dayKey] = recentRecords.filter(r => 
        r.timestamp >= dayStart && r.timestamp < dayEnd
      ).length
    }
    
    return stats
  }

  /**
   * 导出报警数据
   */
  exportAlarmData(format = 'json') {
    const records = this.getAlarmRecords()
    
    if (format === 'json') {
      return JSON.stringify(records, null, 2)
    } else if (format === 'csv') {
      return this.convertToCSV(records)
    }
    
    return records
  }

  /**
   * 转换为CSV格式
   */
  convertToCSV(records) {
    if (records.length === 0) return ''
    
    const headers = [
      'ID', '时间', '类型', '等级', '状态', '纬度', '经度', '地址',
      '设备ID', '分贝值', '是否处理', '处理人', '处理时间'
    ]
    
    const rows = records.map(record => [
      record.id,
      new Date(record.timestamp).toLocaleString(),
      AlarmTypes[record.type]?.name || record.type,
      SeverityLevels[record.level]?.name || record.level,
      record.status,
      record.location.latitude,
      record.location.longitude,
      record.location.address,
      record.device.id,
      record.audioData.decibel,
      record.handling.handled ? '是' : '否',
      record.handling.handlerName,
      record.handling.handleTime ? new Date(record.handling.handleTime).toLocaleString() : ''
    ])
    
    return [headers, ...rows].map(row => row.join(',')).join('\n')
  }

  /**
   * 生成唯一ID
   */
  generateId() {
    return `alarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 生成数据哈希值
   */
  generateHash(data) {
    // 简单的哈希实现，实际项目中应使用更安全的哈希算法
    const str = JSON.stringify(data)
    let hash = 0
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // 转换为32位整数
    }
    return Math.abs(hash).toString(16)
  }

  /**
   * 生成数字签名
   */
  generateSignature(data) {
    // 简单的签名实现，实际项目中应使用更安全的签名算法
    const timestamp = Date.now()
    const hash = this.generateHash(data)
    return `${timestamp}_${hash}`
  }

  /**
   * 通知记录保存
   */
  notifyRecordSaved(record) {
    // 可以在这里添加全局事件触发
    console.log('新报警记录已保存:', record.id)
    
    // 如果是高级别报警，触发即时通知
    if (record.level === 'high' || record.level === 'critical') {
      this.triggerUrgentNotification(record)
    }
  }

  /**
   * 触发紧急通知
   */
  triggerUrgentNotification(record) {
    // 发送系统通知
    wx.showModal({
      title: '⚠️ 紧急报警',
      content: `检测到${AlarmTypes[record.type]?.name || '异常情况'}，请立即查看！`,
      confirmText: '立即查看',
      cancelText: '稍后处理',
      success: (res) => {
        if (res.confirm) {
          // 跳转到报警详情页面
          wx.navigateTo({
            url: `/pages/alarm-detail/alarm-detail?id=${record.id}`
          })
        }
      }
    })
  }
}

// 创建单例
const alarmDataManager = new AlarmDataManager()

export default alarmDataManager
export { AlarmTypes, SeverityLevels } 